import BaseView from "../../../cfw/mvc/BaseView";
import SmallGameController from "../SmallGameController";
import SDKManager from "../../../sdk/SDKManager";
import TextureInfo from "../../../engine/comps/TextureInfo";
import { paintColorName, fillColorName } from "../../../public/Config";
import TextureRenderUtils from "../../../engine/TextureRenderUtils";
import User from "../../db/User";


const { ccclass, property } = cc._decorator;

@ccclass
export default class SmallGameView extends BaseView {


    @property([cc.Sprite])
    pictures: cc.Sprite[] = []
    @property([cc.Sprite])
    picturesRes: cc.Sprite[] = []
    @property(cc.Sprite)
    picture: cc.Sprite = null;

    protected controller: SmallGameController

    start() {
        super.start();
        for (let index = 0; index < this.pictures.length; index++) {
            const element = this.pictures[index];
            this.setSpriteFrame(element, fillColorName + index, () => {
                this.picturesRes[index].node.active = false;
            })
        }
        this.setSpriteFrame(this.picture, paintColorName, null)
    }


    setSpriteFrame(sprite: cc.Sprite, name: string, callback: Function) {
        if (SDKManager.getChannel().cantUseImageDataURL()) {
            sprite.node.scaleY = -1;
            let info: TextureInfo = new TextureInfo()
            info.readFile(name + '.txt', () => {
                if (cc.isValid(this.node)) {
                    sprite.spriteFrame = TextureRenderUtils.getSpriteFrameByTextureInfo(info)
                    if (callback)
                        callback();
                }

            })
        } else {
            let dataUrl = User.instance().getImageData(name)
            if (dataUrl) {
                // console.log(' dataUrl ', dataUrl)
                // let spriteFrame = TextureRenderUtils.getSpriteFrameByDataUrl(dataUrl)
                // sprite.spriteFrame = spriteFrame;

                TextureRenderUtils.getSpriteFrameByDataUrl(dataUrl, (sf: cc.SpriteFrame) => {
                    if (cc.isValid(this.node)) {
                        sprite.spriteFrame = sf
                        if (callback)
                            callback();
                    }

                });
            } else {

            }
        }
    }


    onButtonPictureClick(e, data) {
        let index = parseInt(data)
        this.controller.intoFillColorView(index)
    }

    onButtonPanelClick() {
        this.controller.intoPaintColorView()
    }

    onButtonHomeClick() {
        this.controller.gotoLobby()
    }


}
